
<template>
  <!-- 导航 -->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>任务管理</el-breadcrumb-item>
        <el-breadcrumb-item>任务列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!-- 搜索栏-->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-form :model="taskQuery" inline>
        <el-form-item label="任务标题">
          <el-input v-model="taskQuery.taskTitle"/>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select style="width: 100px" v-model="taskQuery.taskStatus">
            <el-option :value="0" label="全部"/>
            <el-option :value="1" label="正常"/>
            <el-option :value="2" label="暂停"/>
            <el-option :value="3" label="完成"/>
            <el-option :value="4" label="代办"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="loadTasks(0)" type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

  <!-- 工具栏 -->
  <el-row style="margin: 0px 10px;background-color: ghostwhite;padding: 0px 10px">
    <el-col :span="24">
      <el-button-group >
        <el-button :disabled="curUserId!=project.userId"  @click="toAdd" type="primary">新增</el-button>
        <el-button :disabled="curUserId!=project.userId"  @click="changeSubtask(1)" type="primary">编辑</el-button>
        <el-button :disabled="curUserId!=project.userId"  @click="toDeletes" type="primary">删除</el-button>
      </el-button-group>
    </el-col>
  </el-row>
  <!-- 数据列表 -->
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-table :data="tasks" border stripe
                row-key="taskId"
                lazy
                :load="loadChildrenTask"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                ref="taskTable">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="taskId" label="#">
          <template #default="scope">
            <el-link @click="showDetail(scope.row)" type="success">
              {{ scope.row.taskId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="taskTitle" label="任务标题"/>
        <el-table-column prop="user.userName" label="负责人"/>
        <el-table-column label="任务工期" prop="taskDuration"/>
        <el-table-column prop="startTime" label="开始时间"/>
        <el-table-column prop="endTime" label="结束时间"/>
        <el-table-column prop="taskStatus" label="项目状态">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.taskStatus == 1">正常</el-tag>
            <el-tag type="primary" v-else-if="scope.row.taskStatus == 2">暂停</el-tag>
            <el-tag type="info" v-else-if="scope.row.taskStatus == 3">完成</el-tag>
            <el-tag type="primary" v-else-if="scope.row.taskStatus == 4">代办</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <el-link :disabled="curUserId!=project.userId" @click="addSubtask(scope.row.taskId)" style="margin: 0px 5px" type="primary"><el-icon><Plus /></el-icon>新增</el-link>
            <el-link :disabled="curUserId!=project.userId" @click="changeSubtask(scope.row)" style="margin: 0px 5px" type="primary"><el-icon><EditPen /></el-icon>编辑</el-link>
            <el-link :disabled="curUserId!=project.userId" @click="deleteSubtask(scope.row.taskId)" style="margin: 0px 5px" type="primary"><el-icon><Delete /></el-icon>删除</el-link>
            <el-link :disabled="curUserId!=project.userId" @click="commentSubtask(scope.row)" style="margin: 0px 5px" type="primary"><el-icon><ChatLineSquare /></el-icon>评论</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>




  <!-- 新增任务的弹窗 -->
  <el-dialog v-model="taskWinDialogVisible"
             title="新增任务"
             width="50%"
  >

    <el-form :model="newtask">

      <el-form-item label="任务标题">
        <el-input v-model="newtask.taskTitle"/>
      </el-form-item>
      <el-form-item label="任务简介">
        <el-input v-model="newtask.taskDesc"/>
      </el-form-item>

      <el-form-item label="开始时间">
        <el-date-picker
            v-model="newtask.startTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="结束时间">
        <el-date-picker
            v-model="newtask.endTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="任务工期">
        <el-input v-model="newtask.taskDuration"/>
      </el-form-item>
      <el-form-item label="任务进度">
        <el-input v-model="newtask.taskProgress"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="newtask.taskStatus">
          <el-radio :value="1" label="正常"/>
          <el-radio :value="2" label="暂停"/>
          <el-radio :value="3" label="完成"/>
          <el-radio :value="4" label="代办"/>
          <el-radio :value="99" label="删除"/>
        </el-radio-group>
      </el-form-item>


    </el-form>

    <el-button @click="dialogVisible">取消</el-button>
    <el-button type="primary" @click="addTaskSubmit">
      提交
    </el-button>


  </el-dialog>




  <!-- 新增子任务的弹窗 -->
  <el-dialog v-model="subtaskWinDialogVisible"
             title="新增任务"
             width="50%"
  >

    <el-form :model="newtask">

      <el-form-item label="任务标题">
        <el-input v-model="newtask.taskTitle"/>
      </el-form-item>
      <el-form-item label="任务简介">
        <el-input v-model="newtask.taskDesc"/>
      </el-form-item>

      <el-form-item label="开始时间">
        <el-date-picker
            v-model="newtask.startTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="结束时间">
        <el-date-picker
            v-model="newtask.endTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="任务工期">
        <el-input v-model="newtask.taskDuration"/>
      </el-form-item>
      <el-form-item label="任务进度">
        <el-input v-model="newtask.taskProgress"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="newtask.taskStatus">
          <el-radio :value="1" label="正常"/>
          <el-radio :value="2" label="暂停"/>
          <el-radio :value="1" label="完成"/>
          <el-radio :value="2" label="代办"/>
          <el-radio :value="99" label="删除"/>
        </el-radio-group>
      </el-form-item>


    </el-form>

    <el-button @click="subtaskDialogVisible">取消</el-button>
    <el-button type="primary" @click="addSubtaskSubmit">
      提交
    </el-button>


  </el-dialog>



  <!-- 任务编号详情项目的弹窗 -->
  <el-dialog v-model="taskIdListWinDialogVisible"
             title="任务详情"
             width="50%"
  >

    <el-descriptions column="2">
      <el-descriptions-item label="任务标题">{{rowTask.taskTitle}}</el-descriptions-item>
      <el-descriptions-item label="任务简介">{{rowTask.taskDesc}}</el-descriptions-item>
      <el-descriptions-item label="任务开始时间">{{rowTask.startTime}}</el-descriptions-item>
      <el-descriptions-item label="任务结束时间">{{rowTask.endTime}}</el-descriptions-item>
      <el-descriptions-item label="工期">{{rowTask.taskDuration}}</el-descriptions-item>
      <el-descriptions-item label="进度">{{rowTask.taskProgress}}</el-descriptions-item>
      <el-descriptions-item label="负责人">
        <template v-if="!rowTask.user || rowTask.user.userName == null">
          无
        </template>
        <template v-else>
          {{rowTask.user.userName}}
        </template>
      </el-descriptions-item>

    </el-descriptions>




  </el-dialog>




  <!-- 编辑子任务的弹窗 -->
  <el-dialog v-model="changeTaskWinDialogVisible"
             title="新增任务"
             width="50%"
  >

    <el-form :model="rowTask">

      <el-form-item label="任务标题">
        <el-input v-model="rowTask.taskTitle"/>
      </el-form-item>
      <el-form-item label="任务简介">
        <el-input v-model="rowTask.taskDesc"/>
      </el-form-item>

      <el-form-item label="开始时间">
        <el-date-picker
            v-model="rowTask.startTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="结束时间">
        <el-date-picker
            v-model="rowTask.endTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="任务工期">
        <el-input v-model="rowTask.taskDuration"/>
      </el-form-item>
      <el-form-item label="任务进度">
        <el-input v-model="rowTask.taskProgress"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="rowTask.taskStatus">
          <el-radio :value="1" label="正常"/>
          <el-radio :value="2" label="暂停"/>
          <el-radio :value="3" label="完成"/>
          <el-radio :value="4" label="代办"/>
          <el-radio :value="99" label="删除"/>
        </el-radio-group>
      </el-form-item>


    </el-form>

    <el-button @click="changeTaskDialogVisible">取消</el-button>
    <el-button type="primary" @click="changeTaskSubtaskSubmit">
      提交
    </el-button>


  </el-dialog>


<TaskComment :task="commentTask"/>

</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import {onBeforeMount, onMounted, ref, shallowRef} from "vue";
import {ElMessageBox} from "element-plus";
import {Editor,Toolbar} from "@wangeditor/editor-for-vue";
import TaskComment from "@/views/task/task-Comment.vue";
// 导入axios
import axios  from "axios";
import  {useRouter,useRoute} from "vue-router";
import homeRequest from "@/api/home.js";
import projectRequest from "@/api/projects.js";
import taskRequest from "@/api/task.js";
import {ElMessage} from "element-plus";
// 封装搜索条件
let taskQuery = ref({});
// 封装查询的列表数据
let tasks = ref([]);
// 当前路由对象
let route = useRoute();
// 全局路由对象
let router = useRouter();
// 申明对象保存当前的项目对象
let project = ref({});// 不需要申明为响应式对象
// 当前用户编号
let curUserId = ref(-1);
//当前行内数据
let rowTask = ref({});


//评论

let commentTask = ref({});
function commentSubtask(thisRow){
  commentTask.value = thisRow
}







let taskTable = ref(null);
//批量删除
function toDeletes(){
  let selectRows = taskTable.value.getSelectionRows();
  console.log(selectRows)
  if(selectRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
    return;
  }
  ElMessageBox.confirm(
      '你确定要将选中的任务删除吗',
      '提示',
      {
        confirmButtonText:'是的',
        cancelButtonText:'点错了',
        type:'warning',
      }
  ).then(()=>{
    let noCurUserTaskNames = [];
    let taskIds = [];

    selectRows.forEach(row=>{
      console.log(curUserId.value)
      if (row.userId != curUserId){
        noCurUserTaskNames.push(row.taskName);
      }
      taskIds.push(row.taskId);
    })
    console.log(noCurUserTaskNames)
    if (noCurUserTaskNames.length > 0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + noCurUserTaskNames.join(",") + "]并非您管理的，你没有发布权限"
      });
      return;
    }
    //
    taskRequest.deletes(taskIds,res=>{
      console.log(res);
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功删除[" + res.data + "]条数据"
        })
        loadTasks(0);
      }else{
        ElMessage({
          type:"warning",
          message:"删除失败"
        })
      }
    });


  }).catch(()=>{});
}






//删除任务
  function deleteSubtask(taskId){
    console.log(taskId)
    taskRequest.updateTaskStatusById(taskId,res=>{
      if (res.code == 200) {
        console.log(res)
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        // 关闭窗体

        // 刷新表格
        loadTasks(0);
      } else {
        ElMessage({
          type: "error",
          message: "删除失败"
        });
      }
    })
  }

//编辑子任务弹窗标记
let changeTaskWinDialogVisible = ref(false);
//编辑子任务
function changeSubtask(thisRowTask){
  console.log(thisRowTask)
  console.log(taskTable.value.getSelectionRows())
  if (thisRowTask == 1){
    thisRowTask = taskTable.value.getSelectionRows()
    rowTask.value = thisRowTask[0]
    if (thisRowTask.length > 1){
      ElMessage({
        type:"warning",
        message:"选择过多"
      });
      return;
    }
  }else {
    rowTask.value = thisRowTask;
  }

  changeTaskWinDialogVisible.value = true;
}

//取消新增弹窗
function changeTaskDialogVisible(){
  changeTaskWinDialogVisible.value = false;
}
//编辑提交
function changeTaskSubtaskSubmit(){
  taskRequest.updateTask(rowTask.value, res=>{
    if (res.code == 200) {
      console.log(res)
      ElMessage({
        type: "success",
        message: "编辑成功"
      });
      // 关闭窗体
      changeTaskDialogVisible();
      // 刷新表格
      loadTasks(0);
    } else {
      ElMessage({
        type: "error",
        message: "编辑失败"
      });
    }
  })
}







//任务详情弹窗标记
let taskIdListWinDialogVisible = ref(false);

//任务详情
function showDetail(thisRowTask){
  rowTask.value = thisRowTask;
  taskIdListWinDialogVisible.value = true;
}



//新增数据保存
let newtask = ref({});
//新增弹窗标记
let taskWinDialogVisible = ref(false);

//显示新增弹窗
function toAdd(){
  taskWinDialogVisible.value = true;
}

//取消新增弹窗
function dialogVisible(){
  taskWinDialogVisible.value = false;
}
//新增提交
function addTaskSubmit(){
  newtask.value.userId = curUserId;
  newtask.value.projectId = route.params.projectId;
  newtask.value.taskParent = 2;
  newtask.value.taskParentId = 0;
  console.log(newtask);
  taskRequest.saveTask(newtask.value,res=>{
    if (res.code == 200) {
      console.log(res)
      ElMessage({
        type: "success",
        message: "新增成功"
      });
      // 关闭窗体
      dialogVisible();
      // 刷新表格
      loadTasks(0);
    } else {
      ElMessage({
        type: "error",
        message: "新增失败"
      });
    }
  })
}


//新增子任务弹窗标记
let subtaskWinDialogVisible = ref(false);

let nowTaskId = ref();
//显示子任务新增弹窗
function addSubtask(taskId){
  nowTaskId.value = taskId
  subtaskWinDialogVisible.value = true;
}

//取消子任务新增弹窗
function subtaskDialogVisible(){
  subtaskWinDialogVisible.value = false;
}

//提交子任务
function addSubtaskSubmit(){
  newtask.value.userId = curUserId;
  newtask.value.projectId = route.params.projectId;
  newtask.value.taskParent = 2;
  newtask.value.taskParentId = nowTaskId.value;
  taskRequest.updateParentById(nowTaskId.value,res=>{
  })

  console.log(newtask);
  taskRequest.saveTask(newtask.value,res=>{
    if (res.code == 200) {
      console.log(res)
      ElMessage({
        type: "success",
        message: "新增成功"
      });
      // 关闭窗体
      subtaskDialogVisible();
      // 刷新表格
      loadProject(route.params.projectId);
    } else {
      ElMessage({
        type: "error",
        message: "新增失败"
      });
    }
  })
}





//加载子任务
function loadChildrenTask(task,node,resole){
  console.log(task)
  taskRequest.loadTaskByProjectId(taskQuery.value,project.value.projectId,task.taskId,res=>{
    resole(res.data);
  })
}


//加载任务列表
let startTimes = ref([]);
let endTimes = ref([]);
function loadTasks(parentId){

  if (startTimes.value[0]) {
    taskQuery.value.startTimeBegin = startTimes.value[0];
  }
  if (startTimes.value[1]) {
    taskQuery.value.startTimeEnd = startTimes.value[1];
  }
  if (endTimes.value[0]) {
    taskQuery.value.endTimeBegin = endTimes.value[0];
  }
  if (endTimes.value[1]) {
    taskQuery.value.endTimeEnd = endTimes.value[1];
  }
  console.log(taskQuery)
  taskRequest.loadTaskByProjectId(taskQuery.value,project.value.projectId,parentId,res=>{

    tasks.value = res.data;
  })
}


function loadProject(projectId){
  console.log(projectId)
  projectRequest.selectProjectByIdList(projectId, res=>{
    project.value = res.data;
    loadTasks(0);
  })
}



onBeforeMount(()=>{
  let projectId = route.params.projectId;
  console.log(projectId)
  if (projectId){
    loadProject(projectId);
  }else {
    ElMessage({
      type:"info",
      message:"有问题"
    })
    router.push("/home")
  }
  curUserId = localStorage.getItem("userId");
})
</script>

<style scoped>

</style>